<template>
  <view class="orders-container">
    <!-- 订单状态切换 -->
    <view class="tab-bar">
      <view 
        v-for="(tab, index) in tabs" 
        :key="index"
        class="tab-item"
        :class="{ active: currentTab === tab.value }"
        @tap="switchTab(tab.value)"
      >
        {{ tab.name }}
      </view>
    </view>

    <!-- 订单列表 -->
    <scroll-view class="order-list" scroll-y>
      <view v-if="!orderList || orderList.length === 0" class="empty-tip">
        暂无订单~
      </view>
      <view 
        v-else
        v-for="(order, index) in filteredOrders" 
        :key="index"
        class="order-item"
      >
        <!-- 左侧金额 -->
        <view class="order-left">
          <text class="amount">
            <text class="symbol">¥</text>
            {{ order.amount || 0 }}
          </text>
          <text class="order-no">订单号：{{ order.orderNo || '' }}</text>
        </view>
        
        <!-- 右侧信息 -->
        <view class="order-right">
          <view class="order-info">
            <text class="title">{{ order.courseName || '' }}</text>
            <!-- 根据订单状态显示不同的时间信息 -->
            <text class="desc" v-if="order.status === 1">
              创建时间：{{ formatDate(order.createdAt) }}
            </text>
            <text class="desc" v-else-if="order.status === 3 || order.status === 2">
              支付时间：{{ formatDate(order.paidAt) }}
            </text>
            <text class="desc" v-else>
              {{ order.status === 4 ? '取消时间：' : '创建时间：' }}{{ formatDate(order.createdAt) }}
            </text>
          </view>
          <view class="order-action">
            <button 
              v-if="order.status === 1"
              class="action-btn payment-btn" 
              @tap="handlePay(order)"
            >
              去付款
            </button>
            <text 
              v-else
              class="status-text" 
              :class="{
                'status-pending': order.status === 1,
                'status-progress': order.status === 2,
                'status-complete': order.status === 3,
                'status-canceled': order.status === 4
              }"
            >
              {{ getStatusText(order.status) }}
            </text>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { orderApi } from '@/api/order.js'
import { formatDate } from '@/utils/date.js'

export default {
  data() {
    return {
      tabs: [
        { name: '全部', value: 'all' },
        { name: '待付款', value: '1' },
        { name: '进行中', value: '2' },
        { name: '已完成', value: '3' },
        { name: '已取消', value: '4' }
      ],
      currentTab: 'all',
      orderList: []
    }
  },
  
  computed: {
    filteredOrders() {
      if (this.currentTab === 'all') {
        return this.orderList
      }
      return this.orderList.filter(order => order.status.toString() === this.currentTab)
    }
  },
  
  methods: {
    formatDate(date) {
      if (!date) return '---'
      try {
        return formatDate(new Date(date))
      } catch (e) {
        console.error('日期格式化错误:', e, date)
        return '---'
      }
    },

    async getUserOrders() {
      try {
        const userInfo = uni.getStorageSync('userInfo')
        const userId = userInfo ? userInfo.id : null
        console.log('当前用户ID:', userId)
        
        const res = await orderApi.getUserOrders(userId)
        if (res.code === 200) {
          console.log('获取订单成功', res.data)
          this.orderList = res.data
        } else {
          throw new Error(res.message || '获取订单失败')
        }
      } catch (error) {
        console.error('获取订单失败:', error)
        uni.showToast({
          title: '获取订单失败',
          icon: 'none'
        })
      }
    },
    
    switchTab(tab) {
      this.currentTab = tab
      this.getUserOrders()
    },
    
    getStatusText(status) {
      const statusMap = {
        '1': '待付款',
        '2': '进行中',
        '3': '已支付',
        '4': '已取消'
      }
      return statusMap[status] || '未知状态'
    },
    
    handlePay(order) {
      // 跳转到支付页面
      uni.navigateTo({
        url: `/pages/payment/payment?orderNo=${order.orderNo}&amount=${order.amount}&userId=${order.userId}&courseId=${order.courseId}&teacherId=${order.teacherId}&orderId=${order.bookingId}&kc=${encodeURIComponent(order.courseName || '')}}&courseName=${order.courseName}`
      })
    }
  },
  
  onLoad() {
    this.getUserOrders()
  },
  
  onPullDownRefresh() {
    this.getUserOrders().then(() => {
      uni.stopPullDownRefresh()
    })
  }
}
</script>

<style>
.orders-container {
  min-height: 100vh;
  background: #f5f6fa;
  padding-bottom: env(safe-area-inset-bottom);
}

.tab-bar {
  display: flex;
  background: #fff;
  padding: 20rpx 0;
  position: sticky;
  top: 0;
  z-index: 1;
}

.tab-item {
  flex: 1;
  text-align: center;
  font-size: 28rpx;
  color: #666;
  position: relative;
}

.tab-item.active {
  color: #4080FF;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -10rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 4rpx;
  background: #4080FF;
  border-radius: 2rpx;
}

.order-list {
  padding: 20rpx;
}

.order-item {
  display: flex;
  background: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  position: relative;
  overflow: hidden;
}

.order-item::before {
  content: '';
  position: absolute;
  left: 180rpx;
  top: 0;
  bottom: 0;
  border-left: 2rpx dashed #eee;
}

.order-left {
  width: 180rpx;
  padding: 30rpx 20rpx;
  text-align: center;
  background: #4080FF;
  color: #fff;
}

.amount {
  font-size: 48rpx;
  font-weight: bold;
}

.symbol {
  font-size: 32rpx;
}

.order-no {
  font-size: 24rpx;
  margin-top: 10rpx;
  display: block;
  word-break: break-all;
}

.order-right {
  flex: 1;
  padding: 20rpx;
  display: flex;
}

.order-info {
  flex: 1;
  padding-right: 20rpx;
}

.title {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 10rpx;
  display: block;
}

.desc {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
  display: block;
}

.time {
  font-size: 24rpx;
  color: #999;
  display: block;
}

.order-action {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 150rpx;
}

.action-btn {
  background: #fff;
  border: 1px solid #ccc;
  color: #666;
  font-size: 26rpx;
  padding: 6rpx 20rpx;
  border-radius: 30rpx;
  line-height: 1.5;
  height: auto;
  min-height: auto;
}

.action-btn.disabled {
  background: #f5f5f5;
  color: #999;
  border-color: #eee;
}

.action-btn.payment-btn {
  background: #4080FF;
  color: #fff;
  border-color: #4080FF;
}

.status-text {
  font-size: 26rpx;
  color: #999;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  text-align: center;
  background: #f5f5f5;
}

.status-pending {
  color: #ff9800;
  background: rgba(255, 152, 0, 0.1);
}

.status-progress {
  color: #2196f3;
  background: rgba(33, 150, 243, 0.1);
}

.status-complete {
  color: #4caf50;
  background: rgba(76, 175, 80, 0.1);
}

.status-canceled {
  color: #9e9e9e;
  background: rgba(158, 158, 158, 0.1);
}

.empty-tip {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
  font-size: 28rpx;
}
</style> 